<!-- 批次-->
<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:table>
      <div class="batchInfoData">
        <div class="info" v-for="item, index in dataList" :key="index">
          <div class="hander">
            <div class="batchName">{{ item.batchName }}</div>
            <div class="statusList">
              <div class="status" :class="item.status == 'CREATE' ? 'active' : ''">新创建</div>
              <div class="status" :class="item.status == 'WEIGHED' ? 'active' : ''">已称重</div>
              <div class="status" :class="item.status == 'PUT_POND' ? 'active' : ''">已投塘</div>
              <div class="status" :class="item.status == 'SEALED_POND' ? 'active' : ''">已封塘</div>
              <div class="status" :class="item.status == 'COMPLETED' ? 'active' : ''">已完成</div>
            </div>
          </div>
          <div class="infoItem w100p">批次编号: <span>{{ item.batchCode }}</span> </div>
          <div class="infoItem w100p">养殖品种:
            <span v-show="item.batchPondList.length" v-for="batchPondInfo, index in item.batchPondList" :key="index">{{
              batchPondInfo.plantVarietyName + ';' }}</span>
            <span v-show="item.batchPondList.length == 0 || !item.batchPondList">暂无养殖品种</span>
          </div>
          <div class="content">
            <div class="infoItem">养殖设施: <span>{{ facilityObj[item.facilityId] }}</span> </div>
            <div class="infoItem">养殖占比: <span>{{ item.pondRatio + '%' }}</span> </div>
            <div class="infoItem">批次创建时间: <span>{{ $moment(item.buildDate).format("YYYY-MM-DD") }}</span> </div>
          </div>
          <div class="btnList">
            <el-button type="primary" plain @click="showBatchInfo(item)">查看详情</el-button>
          </div>
        </div>
      </div>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size" @current-change="handleCurrentChange" :page="page"
        :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <!-- 生产批次 -->
      <AddEdit :title="'批次'" :parentId="parentId" :batchType="batchType" :facilityList="facilityList"
        :varietyList="varietyList" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :data="formData">
      </AddEdit>
      <BatchInfo :title="'批次信息'" :dialogVisible="isViewBatchInfo" :facilityObj="facilityObj" :batchInfo="batchInfo"
        @closeDialog="closeDialog" />
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
// 添加批次
import AddEdit from './components/addEdit';
// 批次信息
import BatchInfo from './components/batchInfo.vue';
import batch from '@/api/batch/batchManagement';
import varietyManagement from '@/api/basicInformation/varietyManagement';
import facilityManagement from '@/api/digtalOperation/facilityManagement';
export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, BatchInfo, AddEdit },
  data() {
    return {
      title: '管理批次',
      unfoldFlag: false,
      loading: false,
      addEditFlag: 'add',
      dialogVisible: false,
      isViewBatchInfo: false,
      formData: {},
      searchFormData: {},
      page: 1,
      size: 6,
      selectIndex: 0,
      selectList: [],
      total: 10,
      parentId: '',
      batchType: 'BREEDING',
      tableThead: [
        { isShow: true, label: '批次名称', prop: 'batchName', minWidth: '120px' },
        { isShow: true, label: '批次号', prop: 'batchCode', minWidth: '120px' },
        { isShow: true, label: '关联设施', slotName: 'facilityId' },
        { isShow: true, label: '初始养殖信息', slotName: 'objectives' },
        { isShow: true, label: '实际养殖信息', slotName: 'realities' }
      ],
      id: 1000,
      batchInfo: {},
      varietyList: [],
      facilityList: [],
      facilityObj: {},
      dataList: [],
      batchList: [],
      defaultProps: {
        children: 'batchList',
        label: 'batchName'
      },
      formItemList: [
        {
          label: '选择年份',
          type: 'year',
          param: 'year',
          multiple: false,
          isShow: true
        },
        {
          label: '设施名称',
          type: 'select',
          selectOptions: [],
          param: 'facilityId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '批次名称',
          type: 'select',
          selectOptions: [],
          param: 'batchId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
    }
  },

  computed: {
    densityUnitType() {
      return this.$store.state.initData.enum.status
    }
  },
  mounted() {
    this.initData();
    this.queryPageByCondition();
  },
  methods: {
    async initData() {
      // 获取批次列表 
      let { data: batchList } = await batch.queryByCondition({ batchType: 'BREEDING' })
      this.batchList = batchList
      //获取品种；
      let { data: varietyList } = await varietyManagement.queryByCondition({})
      this.varietyList = varietyList || [];
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
      this.facilityObj = {}
      facilityList.forEach(item => {
        this.facilityObj[item.facilityId] = item.facilityName
      })
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('facilityId') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchId') !== -1) {
          let selectOptions = this.batchList.map(data => {
            return {
              text: data.batchName, value: data.batchId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'staffName') {
          let selectOptions = this.person.map(data => {
            return {
              text: data.person.name, value: data.person.name
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    showBatchInfo(row) {
      this.isViewBatchInfo = true;
      this.batchInfo = { ...row, batchPondList: row.batchPondList ? row.batchPondList : [] };
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData,
          batchType: 'BREEDING'
        }
      };
      console.log(batch.queryPageByBatchPond)
      batch.queryPageByBatchPond(params).then(res => {
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      });
    },
    search(data) {
      console.log(data)
      this.page = 1;
      let year = {}
      if (data.year) {
        year = {
          startTime: data.year + '-01-01',
          endTime: data.year + '-12-31'
        }
      } else {
        year = {
          startTime: '',
          endTime: ''
        }
      }
      this.searchFormData = { ...this.searchFormData, ...data, ...year };
      this.queryPageByCondition();
    },
    delList(deleteList = [], key = 'batchId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      if (list.length == 0) return
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await batch.delList(list);
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    editPond(data) {
      this.parentId = data.parentId;
      this.batchType = data.batchType;
      this.addEditFlag = 'edit';
      this.formData = JSON.parse(JSON.stringify(data))
      this.dialogVisible = true
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.isViewBatchInfo = false;
      this.parentId = null;
      this.batchType = 'BREEDING';
      this.queryPageByCondition();
      this.initData();
    },
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-tree-node__content {
  height: 50px;
  border-bottom: 1px solid #f0f0f0;
}

.custom-tree-container {
  width: 100%;

  .icon {
    font-size: 14px;
  }
}

::v-deep .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}

.label {
  padding-left: 10px;
}

.itemData {
  font-size: 14px;
  padding-left: 50px;
  color: #999999;
}

.batchInfoData {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .info {
    width: calc(50% - 20px);
    padding: 10px 20px;
    margin: 10px;
    background: #4381b512;
    border: 1px solid #4382b53a;
    border-radius: 6px;

    .hander {
      display: flex;
      flex-wrap: nowrap;
      justify-content: space-between;
      margin-bottom: 20px;

      .batchName {
        font-size: 18px;
        font-weight: bold;
        color: #4382b5;
      }

      .statusList {
        display: flex;

        .status {
          line-height: 20px;
          padding: 0 15px;
          margin-left: 5px;
          border: 1px solid #1b67855b;
          color: #1b6785a4;
          border-radius: 4px;
        }

        .active {
          background-color: #4382b5;
          color: #ffffff;
        }
      }
    }

    .content {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
    }

    .infoItem {
      width: calc(100% / 3 - 20px);
      line-height: 30px;
      color: #666666;

      span {
        color: #4382b5;
      }
    }
  }
}

.btnList {
  text-align: right;
}
</style>